import fs from "node:fs/promises";
import path from "node:path";
import express from "express";
import { escape } from "node:querystring";

// Constants
const isProduction = process.env.NODE_ENV === "production";
const port = process.env.PORT || 5173;
const base = process.env.BASE || "/";

const PROXY_API_URL = "http://192.168.1.11:8081/";
const BASE_PATH = "/";

// Cached production assets
const templateHtml = isProduction ? await fs.readFile("./dist/client/index.html", "utf-8") : "";
const ssrManifest = isProduction ? await fs.readFile("./dist/client/.vite/ssr-manifest.json", "utf-8") : undefined;

// Create http server
const app = express();

// Add Vite or respective production middlewares
let vite;
if (!isProduction) {
	const { createServer } = await import("vite");
	vite = await createServer({
		server: { middlewareMode: true },
		appType: "custom",
		base,
	});
	app.use(vite.middlewares);
} else {
	const compression = (await import("compression")).default;
	const sirv = (await import("sirv")).default;
	app.use(compression());
	app.use(base, sirv("./dist/client", { extensions: [] }));
}

// Serve static
let staticHandler = express.static("./public");
app.use(["*.js", "*.jpg", "*.png", "*.svg", "*.ico", "*.css", "*.json"], async (req, res) => {
	req.url = req.originalUrl.replace(BASE_PATH, "");
	console.log("static file: " + req.url);
	delete req._parsedUrl;
	staticHandler(req, res, (err) => {
		err && console.error(err);
		res.status(404).send("Not Found:" + req.url);
	});
});
// Serve HTML
app.use("*", async (req, res) => {
	try {
		const url = req.originalUrl.replace(base, "");

		let template;
		let render;
		if (!isProduction) {
			// Always read fresh template in development
			template = await fs.readFile("./index.html", "utf-8");
			template = await vite.transformIndexHtml(url, template);
			render = (await vite.ssrLoadModule("/src/entry-server.ts")).render;
		} else {
			template = templateHtml;
			render = (await import("./dist/server/entry-server.js")).render;
		}

		const rendered = await render(url, ssrManifest);
		console.log(`rendered - ssr state - ${url}: `, rendered.context.ssr_state);

		const html = template
			.replace(`<!--app-store-->`, "window.__ssr_state = " + JSON.stringify(rendered.context.ssr_state).replaceAll("</script>", "<\\/script>") ?? "")
			.replace(`<!--app-head-->`, rendered.head ?? "")
			.replace(`<!--app-html-->`, rendered.html ?? "");

		res.status(200).set({ "Content-Type": "text/html" }).send(html);
	} catch (e) {
		vite?.ssrFixStacktrace(e);
		console.log(e.stack);
		res.status(500).end(e.stack);
	}
});

// Start http server
function startServer() {
	return app.listen(port, () => {
		console.log(`Server started at http://localhost:${port}`);
	});
}
let server = startServer();

if (!isProduction) {
	// 监听文件变化
	import("chokidar").then((chokidar) => {
		chokidar.watch("./").on("change", async () => {
			if (!server) return;
			let closing = server;
			server = null;

			console.log("File changed. Restarting server...");
			await closing.close();
			server = startServer();
		});
	});
}
